/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core.reactor.green;

import com.googlecode.actorom.impl.core.reactor.MessageDemultiplexer;
import com.googlecode.actorom.impl.core.reactor.MessageDispatcher;
import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageHandler;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class GreenMessageDispatcher implements MessageDispatcher {

    private final ConcurrentMap<Object, MessageHandler> handlers = new ConcurrentHashMap<Object, MessageHandler>();
    private Thread selectorThread = null;
    private volatile boolean active = false;

    public void registerHandler(Object key, MessageHandler handler) {
        handlers.put(key, handler);
    }

    public void unregisterHandler(Object key) {
        handlers.remove(key);
    }

    public void dispatch(final MessageDemultiplexer messageDemultiplexer, final MessageQueue messageQueue) {
        if (!active) {
            active = true;
            selectorThread = new Thread() {

                @Override
                public void run() {
                    while (active) {
                        try {
                            messageDemultiplexer.select(messageQueue);
                            Iterator<MessageHandle> handles = messageDemultiplexer.acquireSelectedMessages().iterator();
                            while (handles.hasNext()) {
                                MessageHandle handle = handles.next();
                                MessageHandler handler = handlers.get(handle.getKey());
                                if (handler != null) {
                                    handler.handle(handle);
                                }
                                handles.remove();
                            }
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            };
            selectorThread.start();
        }
    }

    public void shutdown() {
        if (active) {
            active = false;
            selectorThread.interrupt();
        }
    }
}
